using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace TripleMatch
{
    public class LevelObj : MonoBehaviour
    { 
        [SerializeField] Text m_text;
        [SerializeField] Animator m_animator;
        [SerializeField] GameObject m_disableObj;

        private Action<LevelObj> m_onClickCallBack;

        private int m_spriteType;
        public int spriteType
        {
            get {
                return m_spriteType;
            }
        }

        private int m_layer;
        public int layer
        {
            get {
                return m_layer;
            }
        }

        public void InitLevelObj(int _layer, int _spriteType, Action<LevelObj> _onClick)
        { 
            m_onClickCallBack = _onClick;
            m_layer = _layer;

            //TODO:根据贴图类型设置对应贴图
            m_spriteType = _spriteType;
            m_text.text = _spriteType.ToString();
        }

        public void RecycleLevelObj()
        {
            m_onClickCallBack = null;
            m_spriteType = -1;
            m_text.text = string.Empty;

            m_maskObjs?.Clear();
            m_maskCount = 0;
            canClick = false;
        }

        /// <summary>
        /// 会遮挡的方块
        /// </summary>
        private List<LevelObj> m_maskObjs;
        /// <summary>
        /// 自己的遮挡层数
        /// </summary>
        private int m_maskCount;
        public int maskCount {
            get {
                return m_maskCount;
            }
            set {
                m_maskCount = value;
                RefreshState();
            }
        }

        private bool canClick = false;

        public void SetMaskObj(LevelObj m_maskObj)
        {
            if (m_maskObjs == null) m_maskObjs = new List<LevelObj>();
            if (!m_maskObjs.Contains(m_maskObj))
            {
                m_maskObjs.Add(m_maskObj);
                m_maskObj.maskCount++;
            } 
        }

        public void RefreshState()
        {
            canClick = maskCount == 0;
            m_disableObj.SetActive(!canClick);
        }

        public void OnClick()
        {
            if (canClick)
            {
                if (m_maskObjs != null)
                {
                    for (int i = 0; i < m_maskObjs.Count; i++)
                    {
                        m_maskObjs[i].maskCount--;
                    }
                }

                m_onClickCallBack?.Invoke(this);
            } 
        }
    }
}